package cn.jingdalei.org.service.impl;

import cn.jingdalei.basic.service.impl.BaseServiceImpl;
import cn.jingdalei.basic.util.MD5Utils;
import cn.jingdalei.basic.util.PageList;
import cn.jingdalei.basic.util.StrUtils;
import cn.jingdalei.org.domain.Employee;
import cn.jingdalei.org.mapper.EmployeeMapper;
import cn.jingdalei.org.query.EmployeeQuery;
import cn.jingdalei.org.service.IEmployeeService;
import cn.jingdalei.user.domain.Logininfo;
import cn.jingdalei.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
// 事物管理  当前类只读，有事物就支持没有就不管
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    // 1. 基础的CRUD通过继承实现  先继承公共的 再实现扩展的

    // 2. 扩展的功能自己单独写
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    @Transactional
    public void add(Employee employee) {
        init(employee);
        Logininfo logininfo = employee2logininfo(employee);
        logininfoMapper.save(logininfo);
        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.save(employee);
}

    private Logininfo employee2logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        // 属性拷贝
        BeanUtils.copyProperties(employee, logininfo);
        logininfo.setType(0);
        return logininfo;
    }

    private void init(Employee employee) {
        // 盐值
        String stal = StrUtils.getComplexRandomString(32);
        // 加密密码
        String pwdTmp = MD5Utils.encrypByMd5(employee.getPassword() + stal);
        employee.setSalt(stal);
        employee.setPassword(pwdTmp);
    }

    @Override
    @Transactional
    public void update(Employee employee) {
        Logininfo logininfo = employee2logininfo(employee);
        logininfoMapper.update(logininfo);
        employeeMapper.update(employee);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        Employee employee = employeeMapper.loadById(id);
        logininfoMapper.remove(employee.getLogininfo_id());
        employeeMapper.remove(id);
    }
}
